package com.sunhao.springboot_satoken.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sunhao.springboot_satoken.domain.dos.UserDo;
import com.sunhao.springboot_satoken.domain.req.RegisterReq;
import com.sunhao.springboot_satoken.mapper.UserMapper;
import com.sunhao.springboot_satoken.service.CaptchaService;
import com.sunhao.springboot_satoken.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 用户服务实现类
 * @author SunHao
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private CaptchaService captchaService;

    @Override
    public UserDo selectUserByName(String username) {
        UserDo userDo = userMapper.selectOne(new LambdaQueryWrapper<UserDo>().eq(UserDo::getUsername, username));
        if (Objects.nonNull(userDo)) return userDo;
        return null;
    }

    @Override
    public UserDo selectUserById(Long id) {
        UserDo userDo = userMapper.selectById(id);
        if (Objects.nonNull(userDo)) return userDo;
        return null;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDo register(RegisterReq registerReq) {
        // 1. 验证验证码
        boolean captchaValid = captchaService.validateCaptcha(registerReq.getCaptchaKey(), registerReq.getCaptcha());
        if (!captchaValid) {
            log.warn("注册失败：验证码错误或已过期");
            return null;
        }
        
        // 2. 验证用户名是否已存在
        UserDo existUser = selectUserByName(registerReq.getUsername());
        if (existUser != null) {
            log.warn("注册失败：用户名已存在，username={}", registerReq.getUsername());
            return null;
        }
        
        // 3. 验证两次密码是否一致
        if (!registerReq.getPassword().equals(registerReq.getConfirmPassword())) {
            log.warn("注册失败：两次密码不一致");
            return null;
        }
        
        // 4. 创建用户对象
        UserDo userDo = new UserDo();
        userDo.setUsername(registerReq.getUsername());
        // 密码加密存储
        userDo.setPassword(DigestUtils.md5DigestAsHex(registerReq.getPassword().getBytes()));
        userDo.setNickname(registerReq.getNickname());
        // 默认普通用户角色ID为2（假设管理员为1，普通用户为2）
        userDo.setRoleId(2L);
        userDo.setStatus(1); // 1-正常状态
        userDo.setCreateTime(LocalDateTime.now());
        
        // 5. 保存用户
        try {
            userMapper.insert(userDo);
            log.info("用户注册成功，username={}", userDo.getUsername());
            return userDo;
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return null;
        }
    }
}
